package com.lkd.handler;

import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyContract;
import com.lkd.emq.Topic;
import com.lkd.feign.VMService;
import com.lkd.http.vo.TaskDetailsViewModel;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.stream.Collectors;

/**
 * 创建自动补货工单
 * @author Administrator
 */
@Component
@Topic(TopicConfig.TASK_SUPPLY_TOPIC)
@Slf4j
public class SupplyTaskHandler implements MsgHandler {
    @Autowired
    private VMService vmService;

    @Autowired
    private TaskService taskService;


    @Override
    public void process(String jsonMsg) throws IOException {

     try{
         //1.解析协议内容
         SupplyContract byJson = JsonUtil.getByJson(jsonMsg, SupplyContract.class);
         if (byJson == null) {
             return;
         }
        //2.找出被指派人
        VmVO vmInfo = vmService.getVMInfo(byJson.getInnerCode());
        int leastUser = taskService.getLeastUser(vmInfo.getRegionId(), false);
        //3.创建补货工单
        TaskViewModel taskViewModel = new TaskViewModel();
        //用户创建人id
        taskViewModel.setUserId(leastUser);
        //创建类型
        taskViewModel.setCreateType(0);
        //工单类型
        taskViewModel.setProductType(VMSystem.TASK_TYPE_SUPPLY);
        //关联设备编号
        taskViewModel.setInnerCode(byJson.getInnerCode());
        //描述信息
        taskViewModel.setDesc("自动补货工单");

        //获取补货详情
        taskViewModel.setDetails(byJson.getSupplyData().stream().map(c ->{
            TaskDetailsViewModel taskDetailsViewModel = new TaskDetailsViewModel();
            //获取商品id
            taskDetailsViewModel.setSkuId(c.getSkuId());
            //获取货道编号
            taskDetailsViewModel.setChannelCode(c.getChannelId());
            //获取商品图片
            taskDetailsViewModel.setSkuImage(c.getSkuImage());
            //获取商品名称
            taskDetailsViewModel.setSkuName(c.getSkuName());
            //获取期望补货数量
            taskDetailsViewModel.setExpectCapacity(c.getCapacity());
            return taskDetailsViewModel;
        }).collect(Collectors.toList()));

        taskService.createTask(taskViewModel);
     } catch (Exception e){
         e.printStackTrace();
         log.error( "创建自动补货工单出错"+e.getMessage() );
     }
    }
}
